package com.sjd.web.api;

import com.sjd.common.annotation.lock.LocalLock;
import com.sjd.common.core.domain.AjaxResult;
import com.sjd.common.core.domain.entity.SysUser;
import com.sjd.common.core.domain.model.LoginUser;
import com.sjd.framework.web.service.TokenService;
import com.sjd.mall.service.account.AccountService;
import com.sjd.system.service.ISysUserService;
import com.sjd.wx.domain.SjdMember;
import com.sjd.wx.domain.ThirdSession;
import com.sjd.wx.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;

/**
 * 调试用demoapi
 *
 * @author maple
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/api/ma/demo")
@Api(value = "aademo", tags = "a-swagger调试获取授权")
public class DemoApi {

    private final WxUserService wxUserService;
    private final AccountService accountService;
    private final ISysUserService userService;
    private final TokenService tokenService;

    @ApiOperation(value = "获取调试用third-session")
    @GetMapping(value = "/thirdSession")
    @LocalLock(key = "demo:local:lock",errMsg = "land is claimed,please claim other land！")
    public AjaxResult getThirdSession() {
        long memberId = 1;
        String thirdSessionKey = "abcdefgHIJKLMNopqRSTuvwXYZ";
        SjdMember sjdMember = wxUserService.getByMemberId(memberId);
        ThirdSession thirdSession = new ThirdSession();
        thirdSession.setAccountId(accountService.findAccountByMemberId(memberId).getId());
        thirdSession.setAppId(wxUserService.getWxMaAppId());
        thirdSession.setMemberId(sjdMember.getMemberId());
        thirdSession.setMobile(sjdMember.getPhone());
        thirdSession.setSessionKey(sjdMember.getSessionKey());
        thirdSession.setOpenId(sjdMember.getOpenId());
        thirdSession.setThirdSessionKey(thirdSessionKey);
        wxUserService.updateThirdSession(thirdSession);
        return AjaxResult.success(thirdSessionKey);
    }

    @ApiOperation(value = "获取管理平台调试用Authorization")
    @GetMapping(value = "/Authorization")
    public AjaxResult getAuthorization() {
        String token = "abcdefgHIJKLMNopqRSTuvwXYZ";
        SysUser user = userService.selectUserById(1L);
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, Collections.singleton("*:*:*"));
        return AjaxResult.success(tokenService.createToken(loginUser, token));
    }
}
